﻿using System;
using System.Configuration;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Filters;
using LsTool.ApiModels;
using Newtonsoft.Json;
using Zapi.Log.Db;

namespace Zapi.Api.Filters
{
    /// <summary>
    /// 日志接口
    /// </summary>
    public class LogsFilterAttribute : ActionFilterAttribute
    {

        async public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        {

            if (actionExecutedContext.Exception == null)
            {
                LogsEf db = new LogsEf();

                var apiLogs = new ApiLogs
                {
                    CreateTime = DateTime.Now,
                    AppAliasName = ConfigurationManager.AppSettings["AppAliasName"],
                    AppName = actionExecutedContext.Request.RequestUri?.Host,
                    Request = JsonConvert.SerializeObject(actionExecutedContext.ActionContext.ActionArguments),
                    Response = JsonConvert.SerializeObject(actionExecutedContext.Response.Content
                        .ReadAsAsync<BaseOut>(cancellationToken).Result),
                    Url = actionExecutedContext.Request.RequestUri?.AbsoluteUri,
                    Method = actionExecutedContext.Request.Method.ToString(),
                    Ip = GetIp,
                    StatusCode = ((int)actionExecutedContext.Response.StatusCode).ToString()
                };

                db.ApiLogs.Add(apiLogs);
                try
                {
                    db.SaveChangesAsync(cancellationToken);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

            }

        }

        string GetIp
        {
            get
            {
                string userIp;
                HttpRequest request = HttpContext.Current.Request; // ForumContext.Current.Context.Request; 
                                                                   // 如果使用代理，获取真实IP 
                if (request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
                    userIp = request.ServerVariables["REMOTE_ADDR"];
                else
                    userIp = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (string.IsNullOrEmpty(userIp))
                    userIp = request.UserHostAddress;
                return userIp;
            }
        }
    }
}